package com.weixin.message.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.weixin.message.common.message.WeixinMessage;
import com.weixin.message.common.message.WeixinResponse;
import com.weixin.message.common.message.req.ImageMessage;
import com.weixin.message.common.message.req.LinkMessage;
import com.weixin.message.common.message.req.LocationMessage;
import com.weixin.message.common.message.req.MessageFactory;
import com.weixin.message.common.message.req.TextMessage;
import com.weixin.message.common.message.req.VoiceMessage;
import com.weixin.message.common.message.req.event.EventMessage;
import com.weixin.message.common.message.resp.NoReplyResponse;
import com.weixin.message.common.message.resp.RespMessageFactory;
import com.weixin.message.common.type.MessageType;
import com.weixin.message.common.util.MessageUtil;
import com.weixin.message.common.util.ResponseUtils;

/**
 * 消息处理抽象类,自己的处理类要继承这个类
 */
public abstract class WeixinMessageProcessor {
	
	protected static Log logger = LogFactory.getLog(WeixinMessageProcessor.class);

	protected abstract WeixinResponse onText(TextMessage message);

	protected abstract WeixinResponse onImage(ImageMessage message);

	protected abstract WeixinResponse onLink(LinkMessage message);

	protected abstract WeixinResponse onLocation(LocationMessage message);

	protected abstract WeixinResponse onVoice(VoiceMessage message);

	protected abstract WeixinResponse onEvent(EventMessage message);

	public void process(HttpServletRequest request, HttpServletResponse response) {
		WeixinMessage message = MessageFactory.build(request);
		
		if(logger.isDebugEnabled()) {
			logger.debug("用户发来消息:" + message);
		}
		
		WeixinResponse weixinResp = this.process(message);

		if (weixinResp instanceof NoReplyResponse) {
			ResponseUtils.renderText(response, "success");
		} else {
			String xml = MessageUtil.toXML(weixinResp);
			ResponseUtils.renderXml(response, xml);
		}
	}

	protected WeixinResponse process(WeixinMessage message) {
		String msgType = message.getMsgType();

		if (MessageType.text.name().equals(msgType)) {
			return this.onText((TextMessage) message);
		} else if (MessageType.image.name().equals(msgType)) {
			return this.onImage((ImageMessage) message);
		} else if (MessageType.link.name().equals(msgType)) {
			return this.onLink((LinkMessage) message);
		} else if (MessageType.location.name().equals(msgType)) {
			return this.onLocation((LocationMessage) message);
		} else if (MessageType.voice.name().equals(msgType)) {
			return this.onVoice((VoiceMessage) message);
		} else if (MessageType.event.name().equals(msgType)) {
			return this.onEvent((EventMessage) message);
		} else {
			return this.buildNoMatchedMsg(message);
		}
	}

	protected WeixinResponse buildNoMatchedMsg(WeixinMessage message) {
		return RespMessageFactory.buildNoReplyResponse();
	}

}
